package com.example.service;

import com.example.dao.UserinfoDao;
import com.example.entity.Userinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Service("UserinfoService")
public class UserinfoService
{
    @Autowired
    private UserinfoDao userinfoDao;

    public Userinfo select(String name)
    {
        return userinfoDao.userinfoSelect(name);
    }

    public boolean userinfoInsert(Userinfo userinfo)
    {
        List<Userinfo> userinfos = userinfoDao.select();
        for (Userinfo u:userinfos
             )
        {
            if (userinfo.getName().equals(u.getName()))
            {
                return false;
            }
        }
        Date date = new Date();//获得系统时间.
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);//将时间格式转换成符合Timestamp要求的格式.
        userinfo.setIf_online(0);
        userinfo.setLast_time(nowTime);
        userinfoDao.userinfoInsert(userinfo);
        return true;
    }

    public void dateUpdate(Userinfo userinfo,HttpServletResponse response)
    {
        Date date = new Date();//获得系统时间.
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);//将时间格式转换成符合Timestamp要求的格式.
        userinfoDao.dateUpdate(nowTime,userinfo.getName());
        Cookie last_time = new Cookie("last_time",userinfoDao.userinfoSelect(userinfo.getName()).getLast_time().replace(" ",""));
        last_time.setMaxAge(60*20);
        last_time.setPath("/");
        response.addCookie(last_time);
    }

    public void onlineUpdate(Userinfo userinfo,HttpServletResponse response)
    {
        userinfoDao.onlineUpdate(userinfo.getIf_online(),userinfo.getName());
        Cookie if_online = new Cookie("if_online",userinfoDao.userinfoSelect(userinfo.getName()).getIf_online().toString());
        if_online.setMaxAge(60*60);
        if_online.setPath("/");
        response.addCookie(if_online);
    }
    public void logout(Userinfo userinfo)
    {
        new Timer().schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                userinfoDao.onlineUpdate(0,userinfo.getName());
            }
        },5*60*1000-1000);
    }
}
